<template>
  <div class="flex gap2">
    <template v-if="currentApp">
      <el-text v-if="!microOptions" truncated class="max-w-100px! cursor-pointer">{{ currentApp.label }}</el-text>
      <el-dropdown v-else>
        <el-text truncated class="max-w-100px! cursor-pointer">{{ microOptions[currentMicro] || currentApp.label }}</el-text>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="(label, name) in microOptions" :key="name" :disabled="name == currentMicro" @click="chooseMicro(name)">{{ label || name }}</el-dropdown-item>
            <el-dropdown-item divided :disabled="!currentMicro" @click="chooseMicro()">
              <el-text truncated class="max-w-120px!">{{ currentApp.label || currentApp.name }}</el-text>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
    <el-text v-else truncated class="max-w-120px! cursor-pointer" @click="chooseApp">请选择应用</el-text>
    <ElButton link @click="chooseApp">
      <Icon icon="mdi:searches" class="cursor-pointer" />
    </ElButton>
  </div>
</template>
<script setup lang="ts">
  import { setBreadcrumbs, currentApp, currentMicro } from '@/views/seed-dev';
  import { ElText, ElDropdown, ElDropdownItem, ElDropdownMenu, ElButton } from 'element-plus';
  import { Icon } from '@/components/Icon';
  import { computed } from 'vue';
  import { open } from '@/components/Popup';
  import { AppList } from '../../MyApp';

  const microOptions = computed(() => {
    if(!currentApp.value || !currentApp.value.micros) return {}

    const ret = {}
    const app = currentApp.value
    for(const microName in app.micros) {
      const micro = app.micros[microName]
      ret[microName] = micro.label
    }

    return ret
  })

  function chooseApp() {
    open({title: '选择应用'}, AppList)
  }

  function chooseMicro(microName?: string) {
    if(microName) {
      currentMicro.value = microName
      setBreadcrumbs('micro')
    } else {
      currentMicro.value = void 0
      setBreadcrumbs('app')
    }
  }
</script>